﻿using UnityEngine;
using System.Collections;

/// <summary>
/// 메쉬에 충돌체 붙이기.
/// </summary>
[AddComponentMenu("wsLibrary/Mesh/Mesh Collider Creator")]
public class wsMeshCollider : MonoBehaviour
{
	/// <summary>
	/// 충돌체 타입.
	/// </summary>
	public enum ColliderType 
	{ 
		/// <summary>
		/// 사각형
		/// </summary>
		BOX, 
		/// <summary>
		/// 원형
		/// </summary>
		SPHERE, 
		/// <summary>
		/// 캡슐형
		/// </summary>
		CAPSULE 
	};

	/// <summary>
	/// 붙일 충돌체 타입.
	/// </summary>
	public ColliderType colliderType = ColliderType.BOX;
	/// <summary>
	/// 충돌체를 붙일 메쉬의 이름 앞글자.
	/// </summary>
	public string meshName;
	/// <summary>
	/// 지정할 태그 이름.
	/// </summary>
	public string setTagName;

	/// <summary>
	/// 메쉬를 보이지 않게 설정.
	/// </summary>
	public bool hideMesh = true;
	/// <summary>
	/// 충돌체를 트리거로 설정.
	/// </summary>
	public bool setTrigger = false;
	/// <summary>
	/// 리지드바디 추가.
	/// </summary>
	public bool addRigidbody = false;
	/// <summary>
	/// 리지드바디를 키네마틱으로 설정.
	/// </summary>
	public bool setKinematic = false;
	
	void Awake()
	{
		MakeColliderAndHideMesh(meshName, setTagName, hideMesh, setTrigger);
	}

	void MakeColliderAndHideMesh(string meshName, string tagName, bool hideMesh, bool setTrigger)
	{
		Transform[] AllData = gameObject.GetComponentsInChildren<Transform>();

		foreach (Transform Obj in AllData)
		{
			if (Obj.name.Substring(0, meshName.Length) == meshName)
			{
				GameObject go = Obj.gameObject;

				if (colliderType == ColliderType.BOX)
					go.AddComponent<BoxCollider>();
				else if (colliderType == ColliderType.SPHERE)
					go.AddComponent<SphereCollider>();
				else if (colliderType == ColliderType.CAPSULE)
					go.AddComponent<CapsuleCollider>();
				else
					Debug.LogError("Invlalid collider type is set.");

				if (tagName.Length > 0) go.tag = tagName;
				if (hideMesh) go.renderer.enabled = false;
				if (setTrigger) go.collider.isTrigger = true;
				if (addRigidbody)
				{
					go.AddComponent<Rigidbody>();

					if (setKinematic)
						go.rigidbody.isKinematic = true;
				}
			}
		}
	}
}
